package com.logic.landseaserver.models.payment.impl;

import java.util.Date;
import java.util.Map;

import com.logic.landseaserver.common.LandeaConstants;
import com.logic.landseaserver.common.enums.BillStatusEnum;
import com.logic.landseaserver.common.util.DateUtil;
import com.logic.landseaserver.domain.*;
import com.logic.landseaserver.models.independent.service.BillIndependentService;
import com.logic.landseaserver.models.prepayment.service.PrepaymentService;
import com.logic.landseaserver.persistence.read.ContractReadMapper;
import com.logic.landseaserver.persistence.read.RoomReadMapper;
import com.logic.landseaserver.ws.dto.ContractDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.logic.common.security.SecurityUtils;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.common.exception.ResultCodes.PaymentResultCode;
import com.logic.landseaserver.common.util.Arith;
import com.logic.landseaserver.common.util.StringTools;
import com.logic.landseaserver.models.payment.PaymentConstant;
import com.logic.landseaserver.models.payment.PaymentConstant.BillTypeCode;
import com.logic.landseaserver.models.payment.bean.PaymentHelperBean;
import com.logic.landseaserver.models.payment.service.AbstractPaymentResponseHandler;
import com.logic.landseaserver.models.prepayment.bean.AotuPayBill;
import com.logic.landseaserver.models.prepayment.service.AutoPayBillService;
import com.logic.landseaserver.persistence.read.AccountBalanceReadMapper;
import com.logic.landseaserver.persistence.read.AccountReadMapper;
import com.logic.landseaserver.persistence.write.AccountBalanceWriteMapper;
import com.logic.landseaserver.persistence.write.AccountRechargeWriteMapper;

/**
 * 
 *
 * 项目名称：system-server</br>
 * 类名称：RechargePayResponseHandler</br>
 * 类描述：充值支付回调</br>
 * 创建人：Aaron</br>
 * 创建时间：2017年11月28日 下午1:50:25</br>
 * @version 1.0
 *
 */
@Service(BillTypeCode.RECHARGE + PaymentConstant.PAYMENT_RESPONSE_SUFFIX)
public class RechargePayResponseHandler extends AbstractPaymentResponseHandler
{
    @Autowired
    private AccountReadMapper accountReadMapper;
    
    @Autowired
    private AccountBalanceReadMapper accountBalanceReadMapper;
    
    @Autowired
    private AccountBalanceWriteMapper accountBalanceWriteMapper;
    
    @Autowired
    private AccountRechargeWriteMapper accountRechargeWriteMapper;
    
    @Autowired
    private AutoPayBillService autoPayBillService;

    @Autowired
    private RoomReadMapper roomReadMapper;

    @Autowired
    private BillIndependentService billIndependentService;

    @Autowired
    private PrepaymentService prepaymentService;
    // 回调结束后处理
    public static final String RECHARGE_RESPONSE = BillTypeCode.RECHARGE + PaymentConstant.PAYMENT_RESPONSE_SUFFIX;
    
    @Override
    protected void doLocalBusiness(BillPayment payment, PaymentHelperBean helperObject, Map<String, Object> resultMap)
        throws LandseaException
    {
        Integer billId = payment.getBillId();
        String logInfo = getLog(payment, payment.getId());
        LOGGER.info(logInfo + "充值支付回调开始本地业务处理.");
        
        // 检查账户余额类型信息是否存在
        AccountBalance accountBalance = accountBalanceReadMapper.selectByPrimaryKey(billId);
        if (null == accountBalance || accountBalance.getDeleted())
        {
            LOGGER.error(logInfo + "余额记录不存在");
            throw LandseaException.createException(PaymentResultCode.E00140010);
        }
        
        Account account = accountReadMapper.selectByPrimaryKey(accountBalance.getAccountId());
        if (null == account || account.getDeleted())
        {
            LOGGER.error(logInfo + "账户不存在");
            throw LandseaException.createException(PaymentResultCode.E00140010);
        }
        
        // 查询当前账户总余额
        Double pretotalMoney = accountBalanceReadMapper.getTotalMoneyByAccountId(account.getId());
        
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        
        // 更新账户余额
        double totalMoney = Arith.add(payment.getMoney(), accountBalance.getMoney());
        LOGGER.info(logInfo + "开始更新余额表ID=" + accountBalance.getId() + "金钱" + accountBalance.getMoney() + "为" + totalMoney);
        accountBalance.setMoney(totalMoney);
        accountBalance.setLastModifiedBy(userId);
        accountBalance.setLastModifiedDtm(new Date());
        accountBalanceWriteMapper.updateByPrimaryKeySelective(accountBalance);
        
        // 支付成功，添加充值记录
        AccountRecharge accountRecharge = new AccountRecharge();
        accountRecharge.setWid(StringTools.generateUuid());
        accountRecharge.setAccountId(accountBalance.getAccountId());
        accountRecharge.setBalanceType(accountBalance.getBalanceType());
        accountRecharge.setPaymentId(payment.getId());
        accountRecharge.setMoney(payment.getMoney());
        accountRecharge.setTime(payment.getTime());
        accountRecharge.setAccountBalance(totalMoney);
        accountRecharge.setComment("充值");
        accountRecharge.setStatus("成功");
        accountRecharge.initCommonField();
        accountRechargeWriteMapper.insertSelective(accountRecharge);
        LOGGER.info(logInfo + "添加充值记录完毕.");

        //充值支付成功，往独立账单添加一条正值的记录
        Contract contract = prepaymentService.getEffecitveForAdmin(account.getUserId(), account.getRoomId());
        if (null != contract)
        {
            Room room = roomReadMapper.selectByPrimaryKey(contract.getRoomId());
            Date nowD  = new Date();
            BalanceSheetRecord bsr = new BalanceSheetRecord();
            bsr.setContractNo(contract.getContractNo());
            bsr.setProjectId(contract.getProjectId());
            bsr.setRoomId(contract.getRoomId());
            bsr.setHouseNum(room.getHouseNum());
            bsr.setContractId(contract.getId());
            bsr.setBillId(accountBalance.getId());
            bsr.setBillMonth(DateUtil.getInstence().convertYM(nowD));
            bsr.setBillType(LandeaConstants.BillType.RECHARGE_PAY);
            bsr.setAmountReceived(payment.getMoney());
            bsr.setBillStatus(BillStatusEnum.BIST2.getCode());
            bsr.setPayTime(new Date());
            bsr.setExpenditureCode(accountBalance.getBalanceType());
            bsr.setExpenditure(StringTools.getEmunName(accountBalance.getBalanceType()));
            bsr.setReceivableMoney(payment.getMoney());
            bsr.setStartTime(nowD);
            bsr.setEndTime(nowD);
            bsr.setProduceType(LandeaConstants.ProduceType.PAY);
            bsr.setMark("账户余额充值");
            billIndependentService.insertBalanceSheet(bsr);
            LOGGER.info(logInfo + "账户充值成功后添加独立账单完毕.");
        }

        
        // 充值成功，发送微信消息,此处是即时发送
        autoPayBillService.processMoneyChangeWechatMsg(pretotalMoney, Arith.add(pretotalMoney, payment.getMoney()), account, true);
        
        // 在事务提交后，要处理自动抵扣
        resultMap.put(PaymentConstant.AFTER_RESP_COMMIT_TRANSACTION, RECHARGE_RESPONSE);
        resultMap.put("accountId", accountBalance.getAccountId());
    }
    
    @Override
    protected String getProcessClassName()
    {
        return this.getClass().getSimpleName();
    }

    /**    
     * [描述]：</br>
     *
     * @param aotuPayBill
     * @param billPayment
     * @throws LandseaException
     *
    */
    @Override
    public void aotoPayDoLocalBusiness(AotuPayBill aotuPayBill, BillPayment billPayment)
        throws LandseaException
    {
        
    }
}
